package com.woniu.controller;

import com.woniu.common.JsonResult;
import com.woniu.constant.SystemConstant;
import com.woniu.dto.TreeDTO;
import com.woniu.dto.TreegridDTO;
import com.woniu.pojo.Auth;
import com.woniu.service.AuthService;
import com.woniu.util.TreeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/auth")
public class AuthController {
      @Autowired
     private AuthService authService;
         @RequestMapping("/loadTree")
         @ResponseBody
      public List loadTree(@RequestParam(value = "id",defaultValue = "-1",required = false)Integer parentId){
          List<TreeDTO>authList=new ArrayList<>();
          List<Auth>list=authService.findAuthByUserId(1,parentId);
          for (Auth auth:list){
              TreeDTO dto=new TreeDTO();
              dto.setId(auth.getAuthId());
              dto.setText(auth.getAuthName());
              dto.setIconCls(auth.getIconCls());
              dto.setState(auth.getState());
              if (auth.getAuthPath()!=null&&!"".equals(auth.getAuthPath())){
                  Map attr=new HashMap();
                  attr.put("authPath",auth.getAuthPath());
                  dto.setAttributes(attr);
              }
              authList.add(dto);
          }
          return authList;
      }
      @RequestMapping("/list")
      @ResponseBody
      public List<TreegridDTO> list(){
             List<Auth>list=authService.findAll();
             return TreeUtils.buildTreegrid(list, SystemConstant.TREE_ROOT);
      }

      @RequestMapping("/saveAuth")
      @ResponseBody
     public JsonResult save(Auth auth){
             int result=authService.saveAuth(auth);
             if (result==-1){
                 return JsonResult.erro("节点名称重复，不能添加");
             }else {
                 return JsonResult.ok();
             }
     }
     @RequestMapping("/update")
     @ResponseBody
     public JsonResult update(Auth auth){
             int result=authService.updateAuth(auth);
             if (result==-1){
                 return  JsonResult.erro("节点名重复，更新失败");
             }else {
                return JsonResult.ok();
             }
     }


    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Integer authId){
        int result = authService.deleteAuth(authId);
        if(result == -1){
            return JsonResult.erro("该节点下面存在子节点，不能删除");
        }else{
            return JsonResult.ok("删除节点成功");
        }
    }
}
